package com.qbm.association.util;

import com.qbm.association.config.Audience;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;

@Slf4j
public class JWTTokenUtil {

    public static final String AUTH_HEAD_KEY="Authorization";

    /**
     * 根据用户id，用户名，生成token返回给前端
     * @param username
     * @param audience
     * @return
     */
    public static String createJWT(String username, Integer type, Audience audience) {
        SignatureAlgorithm sinSignatureAlgorithm = SignatureAlgorithm.HS256;

        long begin_mills = System.currentTimeMillis();
        Date begin_dateDate = new Date(begin_mills);

        byte[] api = DatatypeConverter.parseBase64Binary(audience.getBase64Secret());
        Key key = new SecretKeySpec(api,sinSignatureAlgorithm.getJcaName());

        Map<String, Object> headerMap = new HashMap<String, Object>();
        headerMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headerMap.put("typ", "JWT");

        JwtBuilder builder = Jwts.builder().setHeader(headerMap)
                .claim("username", username)
                .claim("type",type)
                .setSubject(username)
                .setIssuer(audience.getClientid())
                .setIssuedAt(new java.util.Date())
                .setAudience(audience.getName())
                .signWith(sinSignatureAlgorithm, key);

        int time = audience.getExpiresSecond();
        if(time>0) {
            long exp = begin_mills + time * 1000;
            Date exp_dateDate = new Date(exp);
            System.err.println(exp_dateDate);
            System.err.println(begin_dateDate);
            // 设置到期时间
            builder.setExpiration(exp_dateDate).setNotBefore(begin_dateDate);
        }
        // 返回token
        return builder.compact();
    }

    /**
     * 解析token
     * @param token
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String token,String base64Security) {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    public static String getUserName(String token, String base64Security) {
        log.info("获取token的username");
        return parseJWT(token, base64Security).get("username",String.class);
    }

    public static Integer getPower(String token, String base64Security) {
        log.info("获取token的power");
        return parseJWT(token, base64Security).get("power",Integer.class);
    }

    /**
     * 检查token是否已到期
     * @param token
     * @param base64Security
     * @return
     */
    public static boolean  isExpiration(String token, String base64Security) {
        Claims claims = parseJWT(token, base64Security);
//		System.out.println("expiration:"+claims.getExpiration().toLocaleString());
        return claims.getExpiration().before(new Date());
    }
}
